package com.hlxt.nj.sys.action;


import com.hlxt.nj.common.*;
import com.hlxt.nj.sys.model.TUser;
import com.hlxt.nj.sys.service.TUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/login")
public class LoginAction extends BaseAction{


    @Autowired
    private TUserService userService;

    @RequestMapping(value = "/index.do")
    public String index(){
        TUser user = getUser();
        if(user!=null){
            return "index";
        }
        return "login";
    }


    @RequestMapping(value = "/logout.do")
    public String logout(){
        HttpSession session = getHttpSession();
        if (session!=null) {
            TUser user = getUser();
            session.invalidate();
            if(user!=null){
                log.info("用户["+user.getLoginname()+"]成功退出系统");
            }
        }
        return "login";
    }


    @RequestMapping(value = "/login.do")
    @ResponseBody
    public RespMessage login(String loginName, String password, String code) {
        if(StringUtil.isEmpty(loginName,password)){
            return JSONUtil.getResp(RetCodeDef.PARA_AUTH_FAIL, "");//登录失败，留在登陆页
        }
        TUser user=null;
        HttpSession session = getHttpSession();
        //查找用户
        user=userService.findByLoginname(loginName);
        if(user==null){
            log.info("用户不存在："+loginName);
            return JSONUtil.getResp(RetCodeDef.USER_DO_NOT_EXIST, "");//用户不存在，留在登陆页
        }
        //校验密码
        password = new MD5().toMD5(loginName + password);
        if(!password.equals(user.getPssword())){
            log.info("密码错误："+loginName);
            return JSONUtil.getResp(RetCodeDef.USER_PASSWORD_INCORRECT, "");//密码错误，留在登陆页
        }else{
            user.setPssword(null);//session不能保存密码
            session.setAttribute("loginName", user.getLoginname());
            session.setAttribute(BusiConst.SESSION_USER, user);
            return RespMessageUtil.getResp(RetCodeDef.SUCCESS, "");//登陆成功，跳往主页面

        }
    }




}
